#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>
#include <signal.h>
#include <time.h>
#include <wait.h>
#include <stdbool.h>

const int FLAG = O_CREAT | O_RDWR;
const char *NAME = "/my_msg_queue";
const int MAX_MESSAGES = 50;
const int MAX_MSG_SIZE = 30;
const size_t MSG_BUFFER_SIZE = 30;
const int CLIENT_NUM = 10;
int *processes;

bool stop_client = false;
mqd_t mqd;

static inline void handle_error(const char *err){
    perror(err);
    exit(EXIT_FAILURE);
}

void child_process(){
    printf("[!] I am %d.\n", getpid());
}

void sig_int(int sig){
    if(sig != SIGINT){
        return ;
    }
    for(int i; i < CLIENT_NUM; i++){
        kill(processes[i], SIGINT);
    }
    puts("[-] main process received SIGINT.");
};

void sig_int_child(int sig){
    if(sig != SIGINT){
        return ;
    }
    printf("[-] child process %d received SIGINT.\n", getpid());
}

int main(){
    mqd = mq_open(NAME, FLAG, 7777, NULL);
    if(mqd < (mqd_t)0){
        handle_error("mq_open() error.\n");
    }
    

    processes = (int *)calloc(sizeof(int), CLIENT_NUM);

    for(int i = 0; i < CLIENT_NUM; i++){
        pid_t pid = fork();
        if(pid == 0){
            child_process();
            exit(EXIT_SUCCESS);
        }
        else{
            processes[i] = pid;
        }
    }
    
    signal(SIGINT, sig_int);
    wait(NULL);
    puts("[-] stop all clients.");
    exit(EXIT_SUCCESS);
}
